package org.ligson.httptest.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class LoginUtil {
    public static String getAccessToken(String baseUrl, String code, String password) {
        String accessToken = null;
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Basic bXlpZDpteXNlY3JldA==");
        Map<String, String> params = new HashMap<>();

        params.put("username", code);
        params.put("password", password);
        params.put("scope", "read");
        params.put("grant_type", "password");


        String result = HttpUtil.doPostForm(baseUrl + "/crux-auth/oauth/token", headers, params);
        if (StringUtils.isNoneBlank(result)) {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = null;
            try {
                node = mapper.readTree(result);
            } catch (JsonProcessingException e) {
                log.error("返回结果格式错误");
            }
            if (node != null && node.has("access_token")) {
                accessToken = node.get("access_token").asText();
            }
        }
        if (StringUtils.isBlank(accessToken)) {
            log.error("根据用户名:{}和密码:{}获取不到access_token", code, password);
        } else {
            log.info("根据用户名:{}和密码:{}获取到access_token:{}", code, password, accessToken);
        }
        return accessToken;
    }
}
